import type { ContextMenuInstance} from '@/components/interfaceType'
import SetupCenterView from './SetupCenter.vue'
import { render } from 'vue'

let currentInstance: ContextMenuInstance | null = null
let seed = 1
const setupCenter = (resolve: (value: any) => void, reject: (reason?: any) => void,options: any) => {
    // 销毁之前的菜单
    if (currentInstance) {
        currentInstance.destroy()
    }
    currentInstance = null
    // 创建一个临时的 div，用于挂载菜单
    const container = document.createElement('div')
    let id = seed++
    // 获取 body 标签，用于挂载整个菜单
    const body = document.body
    let setupCenterDialog: boolean = true
    const props: any = {
        setupCenterDialog,
        onClose: () => {
            setupCenterDialog = false
            resolve(false)
            if (currentInstance) {
                currentInstance.destroy()
                container.remove()
            }
        },
    }
    // 渲染虚拟节点
    const vNode = h(
        SetupCenterView,
        props
    )

    // vNode 为需要渲染的虚拟节点，container 为渲染的容器
    render(vNode, container)

    body.appendChild(container)
    // 菜单实例
    const instance: ContextMenuInstance = {
        id,
        destroy: () => {
            currentInstance = null
            render(null, container)
        },
    }

    currentInstance = instance
    return instance
}

export default (config: any)=>{
    return new Promise((resolve: (value: any) => void, reject: (reason?: any) => void) => {
        setupCenter(resolve, reject, config)
    })
  }

